package com.trace.demo.controller;

import com.trace.demo.entity.Dealer;
import com.trace.demo.entity.User;
import com.trace.demo.repository.DealerRepository;
import com.trace.demo.repository.UserRepository;
import com.trace.demo.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.HashMap;

@RestController
@RequestMapping("/api/dealers")
public class DealerController {

    @Autowired
    private DealerRepository dealerRepository;

    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public ResponseEntity<ApiResponse<List<Dealer>>> getAllDealers() {
        List<Dealer> dealers = dealerRepository.findAll();
        return ResponseEntity.ok(new ApiResponse<>(true, "All dealers retrieved successfully", dealers));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Dealer>> getDealerById(@PathVariable Long id) {
        Optional<Dealer> dealer = dealerRepository.findById(id);
        if (!dealer.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Dealer not found with id: " + id, null));
        }
        return ResponseEntity.ok(new ApiResponse<>(true, "Dealer retrieved successfully", dealer.get()));
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<ApiResponse<Dealer>> getDealerByUserId(@PathVariable Long userId) {
        Optional<User> user = userRepository.findById(userId);
        if (!user.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "User not found with id: " + userId, null));
        }

        List<Dealer> dealers = dealerRepository.findByUserId(userId);
        if (dealers.isEmpty()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "No dealer associated with user id: " + userId, null));
        }

        return ResponseEntity.ok(new ApiResponse<>(true, "Dealer retrieved successfully", dealers.get(0)));
    }

    @PostMapping
    public ResponseEntity<ApiResponse<Dealer>> addDealer(@RequestBody Dealer dealer, @RequestParam(required = false) Long userId) {
        // 如果提供了用户ID，则将该用户与经销商关联
        if (userId != null) {
            Optional<User> user = userRepository.findById(userId);
            if (!user.isPresent()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "User not found with id: " + userId, null));
            }
            dealer.setUser(user.get());
        }

        Dealer newDealer = dealerRepository.save(dealer);
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(new ApiResponse<>(true, "Dealer added successfully", newDealer));
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Dealer>> updateDealer(@PathVariable Long id, @RequestBody Dealer dealer) {
        Optional<Dealer> existingDealer = dealerRepository.findById(id);
        if (!existingDealer.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Dealer not found with id: " + id, null));
        }

        // 保留原用户关联
        dealer.setId(id);
        dealer.setUser(existingDealer.get().getUser());

        Dealer updatedDealer = dealerRepository.save(dealer);
        return ResponseEntity.ok(new ApiResponse<>(true, "Dealer updated successfully", updatedDealer));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteDealer(@PathVariable Long id) {
        Optional<Dealer> dealer = dealerRepository.findById(id);
        if (!dealer.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Dealer not found with id: " + id, null));
        }

        dealerRepository.deleteById(id);
        return ResponseEntity.ok(new ApiResponse<>(true, "Dealer deleted successfully", null));
    }

    @GetMapping("/count")
    public ResponseEntity<ApiResponse<Long>> countDealers() {
        Long count = dealerRepository.countDealers();
        return ResponseEntity.ok(new ApiResponse<>(true, "Dealers count retrieved successfully", count));
    }

    @GetMapping("/count/today")
    public ResponseEntity<ApiResponse<Long>> countTodayNewDealers() {
        LocalDateTime startOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT);
        Long count = dealerRepository.countTodayNewDealers(startOfDay);
        return ResponseEntity.ok(new ApiResponse<>(true, "Today's new dealers count retrieved successfully", count));
    }

    @GetMapping("/count/province")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> countDealersByProvince() {
        List<Map<String, Object>> distribution = dealerRepository.countDealersByProvince();
        return ResponseEntity.ok(new ApiResponse<>(true, "Dealers by province count retrieved successfully", distribution));
    }

    /**
     * 获取当前登录经销商信息
     */
    @GetMapping("/current")
    public ResponseEntity<ApiResponse<Dealer>> getCurrentDealer(@RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 为了调试，先返回一个固定的经销商信息
            // 创建一个示例经销商对象
            Dealer dealer = new Dealer();
            dealer.setId(1L);
            dealer.setCompanyName("测试经销公司");
            dealer.setName("测试联系人");
            dealer.setPhoneNumber("13800138000");
            dealer.setAddress("测试地址");
            dealer.setProvince("宁夏");
            dealer.setCity("银川市");
            dealer.setBusinessLicense("BUSINESS123456");
            dealer.setDescription("测试经销商描述");
            dealer.setBusinessScope("商品销售");
            dealer.setCreatedAt(LocalDateTime.now());
            dealer.setUpdatedAt(LocalDateTime.now());
            
            return ResponseEntity.ok(new ApiResponse<>(true, "获取经销商信息成功", dealer));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取经销商信息失败: " + e.getMessage(), null));
        }
    }
    
    /**
     * 获取经销商配送设置
     */
    @GetMapping("/delivery-settings")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getDeliverySettings(@RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 创建默认配送设置
            Map<String, Object> deliverySettings = new HashMap<>();
            deliverySettings.put("defaultLogistics", "顺丰快递");
            deliverySettings.put("defaultShippingAddress", "宁夏回族自治区银川市兴庆区");
            deliverySettings.put("autoConfirmDays", 7);
            deliverySettings.put("deliveryNotification", true);
            
            return ResponseEntity.ok(new ApiResponse<>(true, "获取配送设置成功", deliverySettings));
            
            // 以下是原来的代码，暂时注释掉
            /*
            // 从token中获取用户ID
            Long userId = extractUserIdFromToken(token);
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(new ApiResponse<>(false, "未授权访问", null));
            }
            
            // 创建默认配送设置
            Map<String, Object> deliverySettings = new HashMap<>();
            deliverySettings.put("defaultLogisticsCompany", "顺丰快递");
            deliverySettings.put("autoConfirmDelivery", true);
            deliverySettings.put("deliveryTimeRange", "9:00-18:00");
            deliverySettings.put("deliveryNotification", true);
            deliverySettings.put("returnAddress", "宁夏回族自治区银川市兴庆区");
            
            return ResponseEntity.ok(new ApiResponse<>(true, "获取配送设置成功", deliverySettings));
            */
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取配送设置失败: " + e.getMessage(), null));
        }
    }
    
    /**
     * 更新经销商配送设置
     */
    @PutMapping("/delivery-settings")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateDeliverySettings(
            @RequestHeader(value = "Authorization", required = false) String token,
            @RequestBody Map<String, Object> deliverySettings) {
        try {
            // 从token中获取用户ID
            Long userId = extractUserIdFromToken(token);
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(new ApiResponse<>(false, "未授权访问", null));
            }
            
            // 在实际应用中，这里会保存配送设置到数据库
            // 此处仅返回模拟成功保存的响应
            
            return ResponseEntity.ok(new ApiResponse<>(true, "更新配送设置成功", deliverySettings));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "更新配送设置失败: " + e.getMessage(), null));
        }
    }
    
    /**
     * 从Authorization头中提取用户ID
     */
    private Long extractUserIdFromToken(String token) {
        if (token == null || token.isEmpty()) {
            return null;
        }
        
        // 示例中使用简单的token格式: "Bearer mock-jwt-token-{userId}"
        if (token.startsWith("Bearer mock-jwt-token-")) {
            try {
                String userIdStr = token.substring("Bearer mock-jwt-token-".length());
                return Long.parseLong(userIdStr);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        
        return null;
    }
}
